package com.example.filesystem.util;


import java.nio.charset.StandardCharsets;
import java.util.BitSet;

// RFC3986编码工具类
public class RFC3986 {
    private static final BitSet allowedCharacters = new BitSet(256);

    static {
        // 允许的字符集（RFC3986）
        for (int i = 'a'; i <= 'z'; i++) allowedCharacters.set(i);
        for (int i = 'A'; i <= 'Z'; i++) allowedCharacters.set(i);
        for (int i = '0'; i <= '9'; i++) allowedCharacters.set(i);
        allowedCharacters.set('-');
        allowedCharacters.set('.');
        allowedCharacters.set('_');
        allowedCharacters.set('~');
    }

    public static String encode(String input) {
        StringBuilder encoded = new StringBuilder();
        for (byte b : input.getBytes(StandardCharsets.UTF_8)) {
            int c = b & 0xff;
            if (allowedCharacters.get(c)) {
                encoded.append((char) c);
            } else {
                encoded.append(String.format("%%%02X", c));
            }
        }
        return encoded.toString();
    }
}